package com.chuanyang.driverh;

import android.app.Activity;
import android.app.Application;
import android.text.TextUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.chuanyang.driverh.amap.AMapUtil;
import com.chuanyang.driverh.amap.LocationEntity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.DriverInfoResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.ForegroundCallbacks;
import com.chuanyang.driverh.utils.SDKUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshDriverInfoEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * 应用的Application
 *
 * @author joyskim
 */
public class BaseApplication extends Application implements AMapLocationListener {
    private static BaseApplication application;
    public static BaseApplication getInstance() {
        return application;
    }
    //	private  int count;//待处理订单
    private Activity activity;
    public Activity getActivity() {
        return activity;
    }
    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        SDKUtil.initImageLoader(application);
        ForegroundCallbacks.init(application);
        SDKUtil.initHttp(application);
        SDKUtil.initIfly(application);
        SDKUtil.initBugly(application);
        SDKUtil.initPush(application);
    }


    private LocationEntity locationEntity = new LocationEntity(); //保存用户当前时间的位置信息(每次获取到都要进行更新)

    public LocationEntity getLocationEntity() {
        return locationEntity;
    }

    public void setLocationEntity(LocationEntity locationEntity) {
        this.locationEntity = locationEntity;
    }


    private DriverInfoData driverInfoData; //保存司机信息

    public DriverInfoData getDriverInfo() {
        if (driverInfoData == null) {
            setDriverInfo();
        }
        return driverInfoData;
    }

    public void setDriverInfo() {
        this.driverInfoData = SharedPrefUtil.getPreferences("DriverInfoData", driverInfoData);
    }

    /**
     * 获取司机信息
     */
    public void getDriverInfoFromNet() {//有个人信息修改的情况，重新从网络获取个人信息。
        Map<String, String> params = new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.selectUser(application, params, new MyCallback<DriverInfoResult>(application, new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                setDriverInfo();
                EventBusUtil.postEvent(new RefleshDriverInfoEvent(true));
            }
            @Override
            public void onSuccess(DriverInfoResult result, int id) {
                try {
                    if (result.getCode() == ConstUtil.OK) {
                        driverInfoData = result.getData();
                        SharedPrefUtil.setPreferences("DriverInfoData", driverInfoData);
                        EventBusUtil.postEvent(new RefleshDriverInfoEvent(true));

                        if ( result.getData().getDriver().getCarId()!=0){
                            SharedPrefUtil.setCarId( result.getData().getDriver().getCarId());
                        }
                        if (!StringUtil.isBlank(result.getData().getDriver().getGPSInstallTime())){
                            SharedPrefUtil.setInstalGps(true);
                        }

                    } else {
                        setDriverInfo();
                        EventBusUtil.postEvent(new RefleshDriverInfoEvent(true));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upLoadLatLog() {
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("last_lat", locationEntity.getLatitude());
        params.put("last_lon", locationEntity.getLongitude());
        params.put("geographyPosition", locationEntity.getAddress());
        MyHttpUtil.insertPositionInfo(application,params, new MyCallback<Result>(application,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
//                PrintUtil.toast(application,"位置上传失败");
            }
            @Override
            public void onSuccess(Result result, int id) {
//                PrintUtil.toast(application,"位置上传成功");
            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (loc.getLatitude() != 0 && loc.getLongitude() != 0) {
            String province = loc.getProvince();
            String city = loc.getCity();
            String district = loc.getDistrict();
            String address = loc.getAddress();
            String building = loc.getPoiName();
            if (TextUtils.isEmpty(building)) {
                building = loc.getRoad();
            }

            if (!StringUtil.isBlank(loc.getStreet()) && !StringUtil.isBlank(loc.getStreetNum()) && !StringUtil.isBlank(loc.getAoiName())){
                address=loc.getCity()+loc.getStreet()+loc.getStreetNum()+loc.getAoiName();
            }

            double lat = loc.getLatitude();
            double log = loc.getLongitude();

            locationEntity.setProvince(province);
            locationEntity.setCity(TextUtils.isEmpty(city) ? province : city); //直辖市的city为空 province即为城市名
            locationEntity.setDistrict(district);
            locationEntity.setAddress(address);
            locationEntity.setBuilding(building);
            locationEntity.setLatitude(lat);
            locationEntity.setLongitude(log);
            SharedPrefUtil.setCity(city);
            if (!StringUtil.isBlank(SharedPrefUtil.getUserId())  && !SharedPrefUtil.getInstalGps()){
                upLoadLatLog();
            }
        }
    }

    public void startLoc() {
        AMapUtil.startLocation(this, this, 60000);
    }



    public void stopLoc() {
        AMapUtil.stopLocation();
    }

    @Override
    public void onTerminate() {
        stopLoc();
        super.onTerminate();
    }
}

